package com.xteam.ecsystem.directive;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xteam.ecsystem.base.Constant;
import com.xteam.ecsystem.service.front.FrontGoodsInfoService;
import com.xteam.ecsystem.utils.DirectiveUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 商品过滤条件标签
 * @author ls
 */
@Service
public class GoodsFilterDirective implements TemplateDirectiveModel {
	
	@Autowired
	private FrontGoodsInfoService fgiService;

	@SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		String group = DirectiveUtil.getString(params, Constant.PAR_GOODSGROUP.value());
		String brand = DirectiveUtil.getString(params, Constant.PAR_GOODSBRAND.value());
		String pricemin = DirectiveUtil.getString(params, Constant.PAR_PRICEMIN.value());
		String pricemax = DirectiveUtil.getString(params, Constant.PAR_PRICEMAX.value());
		String selectedattr = DirectiveUtil.getString(params, Constant.PAR_SELECTEDATTR.value());
		String selectedtattri = DirectiveUtil.getString(params, Constant.PAR_SELECTEDTATTRI.value());
		List attr = this.fgiService.getFilterAttr(group);
		List filterbrand = this.fgiService.getFilterBrand(group);
		List filterprice = this.fgiService.getFilterPrice(group);
		//var_带有FILTER的参数表示用于生成查询条件的变量，其余为已选属性，需要回传给页面，展示已选效果。
		env.setVariable(Constant.VAR_FILTERATTR.value(),DEFAULT_WRAPPER.wrap(attr));
		env.setVariable(Constant.VAR_FILTERBRAND.value(),DEFAULT_WRAPPER.wrap(filterbrand));
		env.setVariable(Constant.VAR_FILTERPRICE.value(),DEFAULT_WRAPPER.wrap(filterprice.get(0)));
		env.setVariable(Constant.VAR_GOODSBRAND.value(),DEFAULT_WRAPPER.wrap(brand));
		env.setVariable(Constant.VAR_PRICEMIN.value(),DEFAULT_WRAPPER.wrap(pricemin));
		env.setVariable(Constant.VAR_PRICEMAX.value(),DEFAULT_WRAPPER.wrap(pricemax));
		env.setVariable(Constant.VAR_SELECTEDATTR.value(),DEFAULT_WRAPPER.wrap(selectedattr));
		env.setVariable(Constant.VAR_SELECTEDTATTRI.value(),DEFAULT_WRAPPER.wrap(selectedtattri));
		body.render(env.getOut());
	}
}
